package cc.geguol.iodemo.objectstream;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

/**
 * 作者：13687
 * 日期：2017/6/18
 * 项目：IODemo
 * 描述：实现基本数据类型 持久化操作
 */
public class DataInputStreamDemo {
	public static void main(String[] args) throws IOException {
//		writeData();
//		readData();
//		writerUTFTest();
//		readUTFTest();

//		writeCharTest();
		readCharTest();

	}

	public static void writeData() throws IOException {
		DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("./objs/base.data"));
		dataOutputStream.writeInt(123);//4 字节整数
//		dataOutputStream.write("中文");//4 | 6 字节 写字符 需要用字符流
		dataOutputStream.writeBoolean(true);//1 byte
		dataOutputStream.writeDouble(154.11f);// 8 byte
		dataOutputStream.close();
	}

	public static void readData() throws IOException {
		DataInputStream dataInputStreamDemo = new DataInputStream(new FileInputStream("./objs/base.data"));
		int i = dataInputStreamDemo.readInt();
		boolean b = dataInputStreamDemo.readBoolean();
		double d = dataInputStreamDemo.readDouble();
		System.out.println("i:"+i);
		System.out.println("b:"+b);
		System.out.println("d:"+d);
	}

	/**
	 * 这个是直接操作字符
	 * 注意：
	 * 1. 字符编码 是修改版的utf 格式
	 * 2. 这里没有使用字节字符转换流
	 * */
	public static void writerUTFTest() throws IOException {
		DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream("./objs/urf.txt"));
		dataOutputStream.writeUTF("你好");//修改版的utf 占用4个字节
		dataOutputStream.close();
	}

	public static void readUTFTest() throws IOException {
		DataInputStream dataInputStreamDemo = new DataInputStream(new FileInputStream("./objs/urf.txt"));
		String str = dataInputStreamDemo.readUTF();
		System.out.println("str:"+str);
	}

	/**
	 * 使用字符流写一个 u8 的字符串
	 * */

	public static void writeCharTest() throws IOException {
		OutputStreamWriter outputStreamWriter =
				new OutputStreamWriter(new FileOutputStream("./objs/owriter.txt"),"gbk");
		outputStreamWriter.write("中文");// utf-8  3字节 | gbk 2字节
		outputStreamWriter.close();
	}

	public static void readCharTest() throws IOException {
		InputStreamReader inputStreamReader =
//				new InputStreamReader(new FileInputStream("./objs/owriter.txt"),"gbk");
//				这里去读取其他编码格式的字符文件 会出现乱码
				new InputStreamReader(new FileInputStream("./objs/urf.txt"),"gbk");
//		byte[] buff=new byte[]; 注意字符流的缓冲去用的 char[]
//		byte[] buff=new byte[]; 字节流才会用这个呢
		char[] buff = new  char[50];
		inputStreamReader.read(buff);
		// 不用循环 我只读一次

		System.out.println("str:"+new String(buff,0,buff.length));

	}
}
